var app = getApp()
var BLELocker = require('../../../../../common/BLELocker.js')

//常量数据配置
var ConstantData = require('../../../../../common/constant_data.js')
var statistic = require("../../../../../pages/index/statistic.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    validateLock: false,
    tipStatus: false,
    tipBtnName: '确  定',
    recon: false,
    errI: 0,
    errDesc: '',
    driveLastVer: '200305',
    openLockCount: 0,
    isFold: true,
    btnDisabled: false,
    producerIndex:-1,
    producerList: [],
    curBoxTestType: 1,
    //最新的控制盒版本相关配置信息
    boxLastVerConfList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let that = this;
    that.getDriveLastVersion();
    that.getProducer();
    that.getBoxTypes();
    that.getTipsContent();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  toggleFold() {
    this.setData({
      isFold: !this.data.isFold
    })
  },

  /**
   * 获取提示信息
   */
  getTipsContent(){
    let that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce_list/produceAdditionalInfo',
        header: header,
        success: function (res) {
          console.log('getTipsContent',res);
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if(res.data.result==0){
            that.setData({
              tipsContent:res.data.data,
            })
          }else {
            wx.showToast({
              title: 'rst:网络异常',
              icon:'none'
            })
          }

        },
        fail: function (res) {
          wx.showToast({
            title: 'fail:网络异常',
            icon:'none'
          })
        }
      })

    })
  },

  /**
   * 获取生产员
   */
  getProducer(){//
    let that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce/produce_user',
        header: header,
        success: function (res) {
          console.log('getProducer',res);
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if(res.data.result==0){
            that.setData({
              producerList:res.data.data
            })
          }else {
            wx.showToast({
              title: 'rst:网络异常',
              icon:'none'
            })
          }

        },
        fail: function (res) {
          wx.showToast({
            title: 'fail:网络异常',
            icon:'none'
          })
        }
      })

    })
  },

  /**
   * 获取控制盒版本列表 // mark: 获取控制盒版本列表
   */
  getBoxTypes() {
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce/pile_ver',
        header: header,
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.result === 0 && res.data.data) {
            let boxTypes=[];
            that.data.boxTestTypeList = res.data.data.proTestTypeList;
            res.data.data.pileVerStrList.forEach(item=>{
              boxTypes.push({name:item,checked:false});
            })
            
            //新的版本配置信息下发
            that.data.boxLastVerConfList = res.data.data.boxLastVerConfList;
            if(res.data.data.boxLastVerConfList && res.data.data.boxLastVerConfList.length > 0) {
                boxTypes = [];
                res.data.data.boxLastVerConfList.forEach(item=>{
                    boxTypes.push({name:item.boxTypeName,checked:false});
                })
            }

            that.setData({
                boxTypes:boxTypes
            })  

          }
        }
      })
    });
  },

  /**
   * 选择生产人员
   */
  producerChange(e) {
    let index = e.detail.value;
    console.log('producerChange->',index);
    this.setData({
      producerIndex:index,
    })
  },

  /**
   * 选择控制盒类型
   */
  boxChange(e){
    console.log('boxChange',e);
    let that = this;
    let boxType = e.detail.value;
    let boxTypes = this.data.boxTypes;
    boxTypes.forEach((item, index)=>{
      if(item.name==boxType){
        item.checked=true;
        that.data.curBoxTestType = that.data.boxTestTypeList[index];
        
        if(that.data.boxLastVerConfList && that.data.boxLastVerConfList.length > 0) {
            that.data.curTestBoxConf = that.data.boxLastVerConfList[index]
            that.data.curBoxTestType = that.data.curTestBoxConf.conType;
        }
      }else {
        item.checked=false
      }
    })
    this.setData({
      boxType:e.detail.value,
      boxTypes:boxTypes
    })
  },

  /**
   * 开始检测
   * params: mac
   */
  startInspect() {
    //开始检测，向服务器打标记
    let that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce/produce_test',
        header: header,
        method:'post',
        data: {
          mac: that.data.mac,
          produce_num:parseInt(that.data.producerList[that.data.producerIndex].produce_num),
          pileVer:that.data.boxType
        },
        success: function (res) {
          console.log('produce_test',res);
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.result == 0) { // mark: 跳转到控制盒检测页面
              let curTestBoxConf = that.data.curTestBoxConf  
              let lockMinElect = curTestBoxConf ? curTestBoxConf.minElect : res.data.data.lockMinElectricity
              let lockMaxElect = curTestBoxConf ? curTestBoxConf.maxElect : res.data.data.lockMaxElectricity
              console.log("----->ELECT=", lockMinElect, lockMaxElect)
              let lockVer = curTestBoxConf ? curTestBoxConf.verVal : res.data.data.lockVer
              let lockFullVersion = curTestBoxConf ? (curTestBoxConf.verEquType + curTestBoxConf.verCircuit + curTestBoxConf.verEquChildType 
                + curTestBoxConf.verReserveOne + curTestBoxConf.verReserveSecond + curTestBoxConf.verVal) : null
              console.log('produce_test',that.data.mac,encodeURIComponent(that.data.deviceId),that.data.producerList[that.data.producerIndex].produce_name,that.data.producerList[that.data.producerIndex].produce_num,res.data.data.id,res.data.data.hid,that.data.boxType);
              wx.navigateTo({
                url: '../produce/inspecting/inspecting?mac='+that.data.mac+'&deviceId='+encodeURIComponent(that.data.deviceId)
                +'&producer_name='+that.data.producerList[that.data.producerIndex].produce_name
                +'&producer_num='+that.data.producerList[that.data.producerIndex].produce_num
                +'&testId='+res.data.data.id
                +'&hid='+res.data.data.hid
                +'&boxType='+that.data.boxType
                +'&lockMinElectricity='+lockMinElect
                +'&lockMaxElectricity='+lockMaxElect
                +'&lockVer=' + lockVer
                +'&lockFullVersion=' + lockFullVersion
                +"&proTestType=" + that.data.curBoxTestType,
              })
          } else {
            // that.data.testId = res.data.data.id;
            // that.data.errReason = res.data.description;
            wx.showModal({
              showCancel:false,
              title:'温馨提示',
              content:res.data.description
            })
            // that.submit();
          }
        },
        fail: function (res) {
          wx.showToast({
            title: 'fail:网络异常',
            icon:'none'
          })
        }
      })

    })
  },
  /**
   * 提交检测结果
   **/
  submit: function(){
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce/produce_test_record',
        header: header,
        data:{
          step:1,
          produceTestId:parseInt(that.data.testId),
          errReason:JSON.stringify(that.data.errReason),
          pileVer:that.data.boxType,
          blueConTime:0,
        },
        success: function (res) {
          that.data.mac = '';
          wx.showToast({
            title: '已提交不通过',
          })
        },
        fail:function(){
          wx.showToast({
            title: 'fail:网络异常',
            icon:'none'
          })
        }
      })

    })
  },

  /**
   * 扫码
   * params: mac
   */
  scanCode() {
    let that = this;
    if(that.data.producerIndex<0){
      wx.showToast({
        title: '请选择生产员',
        icon:'none'
      })
      return
    }else if(!that.data.boxType){
      wx.showToast({
        title: '选择控制盒类型',
        icon:'none'
      })
      return;
    }
    wx.scanCode({
      success: (res) => {
        console.log('scanCode-->',res);
        let qrc = '';
        var qrCode = res.result;
        if(!qrCode){
          wx.showToast({
            title: '二维码为空',
            icon: 'none'
          })
          return;
        }

        let reg = /^([A-Za-z0-9]{2}:){5}([A-Za-z0-9]{2}){1}$/;
        if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX) == 0 || qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_OLDER_URL_PREFIX) == 0) {
          //设备二维码
          var rst = qrCode.split('/');
          qrc = rst[rst.length - 1];
          that.getMacId(qrc);
        } else if (reg.test(qrCode)) {
          that.data.deviceId = qrCode;
          that.data.mac = qrCode.replace(/:/g, '');
          that.startInspect();
          return;
        } else {
          wx.showToast({
            title: '二维码错误',
            icon:'none'
          })
          return
        }
      },
      fail: (res) => {}
    });
  },

  /**
   * 获取mac
   * params: mac
   */
  getMacId(qrc){
    let that = this;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/connect/device',
        header: header,
        data: {
          qrc: qrc
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.rst == 0) {
            let mac = res.data.macId;
            if (!mac) {
              wx.showToast({
                title: 'null:请重新扫码',
                icon:'none'
              })
              return
            }
            if(res.data.deviceId){
              that.data.deviceId = res.data.deviceId;
            }
            that.data.mac = mac;
            //开始检测
            that.startInspect();

          } else {
            wx.showToast({
              title: 'rst:请重新扫码',
              icon:'none'
            })

          }
        },
        fail: function (res) {
          wx.showToast({
            title: 'fail:请重新扫码',
            icon:'none'
          })

        }
      })

    })
  },

  /**
   * 获取最新驱动版本 // mark: 获取最新驱动版本
   * params: mac
   */
  getDriveLastVersion: function () {
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_admin/produce/produce_testing',
        header: header,
        success: function (res) {
          console.log("get test conf info",res);

          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          if (res.data.result === 0 && res.data.data) {
            let blueSignalStrength = JSON.parse(res.data.data.blueSignalStrength)
            wx.setStorageSync('lastDriVersion', res.data.data.ver);
            wx.setStorageSync('minElectrict', res.data.data.min_electricity);
            wx.setStorageSync('maxElectricity', res.data.data.max_electricity);
            wx.setStorageSync('motorRunningTime', res.data.data.motorRunningTime);
            wx.setStorageSync('lockMotorRunningTime', res.data.data.lockMotorRunningTime);
            wx.setStorageSync('RSSIMax', blueSignalStrength.max);
            wx.setStorageSync('RSSIMin', blueSignalStrength.min);
            wx.setStorageSync('hasJurisdiction', res.data.data.hasJurisdiction);
          }
        }
      })
    });
  },

  //连接蓝牙设备
  connectBLEDevice: function (blueName) {
    getApp().globalData.isAllowBroadcastBack = 0;
    wx.showLoading({
      title: '开始连接..',
      mask: true
    });
    var that = this
    // BLELocker.connect(blueName, function (status, data) {
    //   that.handleStatus(status, data)
    // }, 0)   //设置超时时间time,0使用默认的超时时间

    //使用新的连接
    BLELocker.newConnect(blueName, function (status, data) {
      that.handleStatus(status, data)
    }, 0, false, null, null, that);

    //记录桩的服务信息
    BLELocker.setCollectionServiceData(function (uuid, fce7, fce8, fce9) {
      app.executeRequest(function (header) {
        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/markHomingPile',
          header: header,
          data: {
            mac: blueName,
            uuid: uuid,
            fce7: fce7,
            fce8: fce8,
            fce9: fce9
          },
          success: function () {
            console.log("上传桩服务信息成功")
          }
        })
      })
    })

  },

  //处理设备连接状态变化回调
  handleStatus: function (status, data) {
    var that = this

    if (status == BLELocker.Status.bleScanStart) {
      getApp().hideLoading();
      wx.showLoading({
        title: '连接中....',
        mask: true
      })
    } else if (status == BLELocker.Status.appVersionNotSupported) {
      wx.showToast({
        title: '微信版本低',
        icon:'none'
      })
    } else if (status == BLELocker.Status.bleIsClosed || status == BLELocker.Status.adaperOpenFail) {
      getApp().hideLoading();
      wx.showToast({
        title: '请打开蓝牙',
        icon:'none'
      })
    } else if (status == BLELocker.Status.bleNotSupportWXService || status == BLELocker.Status.bleNotSupportWXCharacteristic) {
      wx.showToast({
        title: '系统版本低',
        icon:'none'
      })
    } else if (status == BLELocker.Status.bleReceiveAuthData) {
      getApp().hideLoading();
      wx.showLoading({
        title: '读取数据....',
        icon:'none',
        mask: true
      })
    } else if (status == BLELocker.Status.bleConnectTimeout) {
      getApp().hideLoading()
      //断开蓝牙连接
      BLELocker.disconnect();
      wx.showToast({
        title: '连接超时',
        icon:'none'
      })
      that.recordOpenLockResult(15);

    } else if (status == BLELocker.Status.bleClosed) {
      getApp().hideLoading()
      wx.showToast({
        title: '蓝牙已关闭',
        icon:'none'
      })
    } else if (status == BLELocker.Status.bleOpened) {

      //这里不需要做任何处理

    } else if (status == BLELocker.Status.bleSend85Timeout) {
      getApp().hideLoading()
      wx.showToast({
        title: '开锁超时',
        icon:'none'
      })
      wx.showLoading({
        title: '重连。。。',
      })
      that.recordOpenLockResult(11);

    } else if (status == BLELocker.Status.bleSend95Timeout) {
      getApp().hideLoading()
      wx.showToast({
        title: '95超时',
        icon:'none'
      })
      that.recordOpenLockResult(14);

    } else if (status == BLELocker.Status.ble85Data) {

      //断开蓝牙连接
      BLELocker.disconnect()

      if (data == null) {
        getApp().hideLoading()
        wx.showToast({
          title: '开锁失败',
          icon:'none'
        })
        that.recordOpenLockResult(12);

      } else {

      }
    } else if (status == BLELocker.Status.ble95Data) {
      wx.showLoading({
        title: '读取数据..',
      })
      if (data == null) {
        getApp().hideLoading()
        wx.showToast({
          title: '连接失败',
          icon:'none'
        })
        that.recordOpenLockResult(13);

      } else {
        console.log("生产检测控制盒版本信息---->", version , that.data.driveLastVer)
        var electrict = data.electrict; //归位桩剩余电量

        var mac = data.mac;
        var rfId = data.rfid;
        var costTime = data.costTime;
        var hookStatus = data.hookStatus;
        var chairSwitchSatus = data.chairSwitchSatus;
        let version = BLELocker.getDriverVersion();
        var errDesc = that.data.errDesc;
        var i = that.data.errI;

        if (that.data.pileLocation != undefined && that.data.pileLocation != null) {
          data.location = that.data.pileLocation;
        }
        data.pile_ver = version;
        //95数据记录
        let dataType = that.data.recon ? "95dataProB" : "95dataProA";
        statistic.statisticData(dataType, JSON.stringify(data));
        let elecV = '(' + (electrict / 1000) + 'v) ';
        if (electrict >= 7000) {
          that.recordOpenLockResult(21);
          i++;
          errDesc += i + (that.data.recon ? ".开锁后电池电压高于7v! " + elecV : '.开锁前电池电压高于7v!' + elecV)
        }
        if (electrict < 6000) {
          that.recordOpenLockResult(21);
          i++;
          errDesc += i + (that.data.recon ? ".开锁后电池电压低于6v!" + elecV : '.开锁前电池电压低于6v!' + elecV)
        }
        if (version != that.data.driveLastVer) {
          that.recordOpenLockResult(20);
          i++;
          errDesc += i + ".版本非最新的" + that.data.driveLastVer + "; "
        }
        if (hookStatus == 1) {
          that.recordOpenLockResult(18);
          i++;
          errDesc += i + (that.data.recon ? ".开锁后锁勾开关未压紧; " : ".开锁前锁勾开关未压紧; ")
        }
        if (!that.data.recon && chairSwitchSatus == 0) {
          that.recordOpenLockResult(19);
          i++;
          errDesc += i + ".开锁前插入开关异常; "
        }
        if (that.data.recon && chairSwitchSatus == 1) {
          that.recordOpenLockResult(22);
          i++;
          errDesc += i + ".开锁后插入开关异常; "
        }

        if (!that.data.recon && 'FFFFFFFF' == rfId) {
          that.recordOpenLockResult(16);
          i++;
          errDesc += i + ".rfid标签不识别; ";
        }
        if (that.data.recon && 'FFFFFFFF' != rfId) {
          that.recordOpenLockResult(23);
          i++;
          errDesc += i + ".设备未弹出; ";
        }
        if (electrict < that.data.homeMinLeftElectricity) {
          that.recordOpenLockResult(17);
          i++;
          errDesc += i + ".电量低于最低电量; "
        }
        console.log("--reCon=", that.data.recon);
        console.log("--errDesc=", errDesc);

        if (i > 0) {
          that.setData({
            errDesc: errDesc,
            errI: i
          });

          if (that.data.recon) {
            getApp().hideLoading();
            that.setData({
              tipStatus: true,
              tipContent: that.data.errDesc + " 【不能通过】",
              errI: 0,
              errDesc: '',
              recon: false
            })
            return;
          }
        } else if (that.data.recon) {
          that.setData({
            recon: false
          })
          wx.showModal({
            title: '提示',
            content: '开锁成功,桩是否通过测试?',
            cancelText: "不良",
            confirmText: "通过",
            success(res) {
              if (res.confirm) {
                that.recordOpenLockResult(2);
              } else if (res.cancel) {
                that.recordOpenLockResult(10);
              }
            }
          })
          return;
        }

        // if (that.data.validateLock) {
        //   //锁钩情况监测
        //   that.setData({
        //     validateLock: false
        //   });
        //   return;
        // }

        getApp().hideLoading();
        wx.showLoading({
          title: '开锁....',
          mask: true
        })
        that.recordEquipmentInfo(rfId);
      }
    }

  },

  /***
   * 发送85开锁
   */
  send85Command: function () {
    var that = this;

    if (that.data.recon) {
      that.setData({
        recon: false
      });
    }
    wx.showLoading({
      title: '开锁中..',
      mask: true
    })
    BLELocker.send85Command(function (isSuccess) {
      if (isSuccess == false) {
        wx.showToast({
          title: '开锁异常',
          icon:'none'
        })
      } else {
        // BLELocker.send95Command();
        // that.setData({
        //   validateLock:true
        // });
        wx.showToast({
          title: '开锁成功',
        });
        wx.showLoading({
          title: '重连...',
        });

        setTimeout(function () {
          getApp().hideLoading()
          that.setData({
            recon: true,
            rescan: true
          });
          that.connectBLEDevice(that.data.curBlueName);
        }, 10000)
      }
    })

  },

  tipBtnClick: function () {
    this.setData({
      tipStatus: false,
    });
  },

})
